Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.
Getting Query String Values
JavaScript’s standard library has the URLSearchParams
constructor that can be used to extract the query parameters and let us search for them.
For instance, we can write:
const urlParams = new URLSearchParams(window.location.search);
const val = urlParams.get('key');
window.location.search
returns the query string portion of the URL.
The get
method gets the value by the key of the query parameter.
Round a Number to at Most 2 Decimal Places
We can use Math.round
to let us round to 2 decimal places.
For instance, we can write:
Math.round(num * 100) / 100
We multiplied num
by 100, round it, and then divide by 100 to return a number that has at most 2 decimal places.
If there are decimal digits that are less than the hundredth digit, then we add Number.EPSILON
to before we multiply by 100.
So we write:
Math.round((num + Number.EPSILON) * 100) / 100
Also, we can use parseFloat
and toFixed
to format a number into a string of the number with 2 decimal places.
We can write:
parseFloat("575.393").toFixed(2);
Convert a String to Boolean
We can convert the string 'true'
and 'false'
to their corresponding boolean value by writing:
val === 'true'
Assuming that val
can be set to 'true'
or 'false'
, we can just compare against 'true'
to do that.
Storing Objects in Local Storage
To store an object in local storage, we’ve to convert it to a string first.
For instance, we can write:
const obj = { 'foo': 1, 'bar': 2, 'baz': 3 };
localStorage.setItem('data', JSON.stringify(obj));
We called JSON.stringify
before calling setItem
to store the stringified object with the key
data in local storage.
JSON.stringify
won’t keep undefined
, functions, Infinity
, and regex, so we’ve to be careful about that.
Merge 2 or More Objects
We can use the spread operator or Object.assign
to merge the properties of 2 or more objects together.
For instance, we can write:
const merged = {...obj1, ...obj2, ...obj3};
or:
const merged = Object.assign({}, obj1, obj2, obj3, etc);
Both pieces of code populate the properties of obj1
, obj2
, and obj3
into an empty object.
Detect a Click Outside an Element
We can call stopPropagation
to prevent the click event from the element that we’re checking the click from the outside of.
So we can write:
window.addEventListener('click', () => {
// do something when clicked outside
});
document.querySelector('#menucontainer').click((event) => {
event.stopPropagation();
});
The window
‘s click
event handler lets us run code when the user clicks outside.
Refresh a Page
There are many ways to refresh a page with JavaScript,
We can do:
location.reload();
history.go(0)
location.href = location.href
location.href = location.pathname
location.replace(location.pathname)
location.reload(false)
location.pathname
is the relative URL.
history.go
also refreshes by reloading the same page.
Pretty Print JSON
We can pretty-print JSON with the JSON.stringify
method.
For example, we can write:
const str = JSON.stringify(obj, null, 2);
The 2 indicates that we indent by 2 spaces.
Passing Command Lines Arguments to a Node.js Program
Node programs have access to the process.argv
property to get all the command line arguments of a program.
For instance, we can write:
for (const a of process.argv){
console.log(a)
}
The first argument is always 'node'
. The 2nd is always the path of the file we run.
The rest are the other command-line arguments.
Check for Decimal Numbers
We can check for decimal numbers by using the isNaN
function and the isFinite
function.
To do the check, we write:
!isNaN(parseFloat(n)) && isFinite(n);
parseFloat
parses the string into a floating-point number.
isNaN
checks whether the returned value is NaN
or not.
isFinite
checks whether the number or numeric string represents a finite number.
Modify the URL Without Reloading the Page
The URL can be modified without reloading the page with JavaScript.
The window.history.pushState
lets us add a new URL to the browsing history.
We can write:
window.history.pushState('foo', 'title', '/foo.html');
The first argument is the state object.
We can take get the value of the argument with popstate
.
'title'
is the title, which is ignored in most browsers.
'/foo.html'
is the URL to write to the browsing history.
Conclusion
The URLSearchParams
constructor lets us parse query strings into a useful object that we can look up.
We can use Math.round
to round a number to 2 decimal places.
Also, we can change the URL and add it to the browsing history without reloading the page.